<!-- 关联商品 -->
<template>
  <div>
    <el-drawer
      v-model="visible"
      :size="props.width"
      :before-close="hide"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :destroy-on-close="true"
      :modal="true"
    >
      <template #title>
        <div class="flex flex-col">
          <div class="drawer-header">
            <div class="flex items-center dot" v-if="showDot">
              <div class="w-[5px] h-[5px] rounded-1/2 bg-[#3721FF]"></div>
              <span class="ml-2 drawer-title">{{ props.title }}</span>
            </div>
          </div>
          <div class="text-[12px] mt-[4px] text-[#999] desc">{{ props.titleDesc }}</div>
        </div>
      </template>
      <div class="mt-2 drawer-content">
        <el-form label-width="120px" class="w-80%" v-model="form" label-position="left">
          <el-form-item label="分类名称" required>
            <el-input v-model="form.name" placeholder="请输入分类名称" clearable />
          </el-form-item>
          <el-form-item label="上级分类" class="mt-6">
            <el-select v-model="form.parentId" placeholder="请选择上级分类" disabled>
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="关联商品" class="mt-10">
            <el-button @click="addRelatedGoods" plain color="#3721FF"> + 新增关联商品</el-button>
          </el-form-item>
        </el-form>
        <div class="mt-16">
          <el-table
            :data="tableData"
            :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#333' }"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="title" label="商品名称" />
            <el-table-column label="图片">
              <template #default="{ row }">
                <ImagePreview :src="row.cover" width="38px" height="38px" />
              </template>
            </el-table-column>
            <el-table-column prop="id" label="商品ID" >
              <template #default="{ row }">
                <p v-copyText="row.id">
                  {{ row.id }}
                   <Icon icon="ep:copy-document" :size="12" class="cursor-pointer" />
                </p>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row, $index }">
                <el-button type="danger" link size="small" @click="deletePruduct(row, $index)"
                  >移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="queryList"
          />
        </div>
      </div>
      <template #footer>
        <div class="drawer-footer el-dia-btn">
          <el-button @click="hide">取消</el-button>
          <el-button color="#3721FF" type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <SelectProducts
      ref="selectProductsRef"
      @selection-change="onSelectionChange"
      :showDot="true"
      @confirm="onConfirm"
      width="50%"
      title="选择商品"
    />
  </div>
</template>

<script setup lang="ts">
import SelectProducts from '@/components/SelectProducts/index.vue'
import { onMounted } from 'vue'
import { getProductByCategoryId } from '@/api/mall/product/spu'
import ImagePreview from '@/components/ImagePreview/index.vue'
import * as ProductCategoryApi from '@/api/mall/product/category'
const categoryList = ref<any[]>([]) // 分类树

defineOptions({ name: 'RelatedGoods' })
const selectProductsRef = ref()
const form = ref({
  name: '', // 分类名称
  parentId: '' // 上级分类
})
const visible = ref(false)
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const total = ref(0)
const categoryId = ref(null)

const tableData = ref([])
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  titleDesc: {
    type: String,
    default: ''
  },
  width: {
    type: String,
    default: '50%'
  },
  showDot: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['confirm'])

const queryParams = ref({
  pageNo: 1,
  pageSize: 10
})
const addRelatedGoods = () => {
  selectProductsRef.value?.show()
}
const deletePruduct = (row: any, index: number) => {
  // tableData.value.splice(index, 1)
  // 二次提示
  ElMessageBox.confirm('确定要移除该商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ProductCategoryApi.removeCategoryProductList(row.id).then(() => {
      ElMessage.success('移除成功')
      queryList()
    })
  })
}
const show = async (id) => {
  categoryId.value = id
  visible.value = true
  if (id) {
    formLoading.value = true
    try {
      form.value = await ProductCategoryApi.getCategory(id)
    } finally {
      formLoading.value = false
    }
  }
  queryList()
  // 获得分类树
  categoryList.value = await ProductCategoryApi.getCategoryList({ parentId: 0 })
  form.value.parentId = form.value.parentId == 0 ? '无' : form.value.parentId
}

const hide = () => {
  visible.value = false
}

/*
 * 根据分类查询商品列表
 * */
const queryList = async () => {
  let res = await getProductByCategoryId({
    categoryId: categoryId.value,
    ...queryParams.value
  })
  tableData.value = res.list
  total.value = res.total
  console.log(res, '===res')
}

const onSelectionChange = async (val) => {
  // tableData.value = tableData.value.concat(val)
}

/**
 * 选择商品点击确定
 * */
const onConfirm = (val) => {
  let newVal = val.filter((item) => {
    let it = tableData.value.find((at) => {
      return at.id == item.id
    })
    return !it
  })

  tableData.value = tableData.value.concat(newVal)
}

/**
 * 关联商品点击确定
 * */
const handleConfirm = () => {
  console.log(tableData.value, ' tableData.value tableData.value')
  if (!tableData.value || tableData.value.length > 0) {
    emit('confirm', tableData.value)
    hide()
  } else {
    ElMessage.error('请选择商品')
  }
}

defineExpose({
  show
})
</script>

<style scoped>
@import '@/styles/website.scss';
</style>
